/*
 * Copyright (C) 2016  Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#include "PlanetWars2dRT-core/utils/observer_essential.h"
#include <stddef.h>


EXTERN_C_BEGIN


void
observer_init_first_time_only_unsafe(observer_t* an_observer)
{
  an_observer->handler   = NULL;
  an_observer->data      = NULL;
  an_observer->data_free = NULL;
}

bool
observer_init_first_time_only(observer_t* an_observer)
{
  if(an_observer == NULL)
    {
      return false;
    }
  observer_init_first_time_only_unsafe(an_observer);
  return true;
}

void
observer_destructor_unsafe(observer_t* an_observer)
{
  if(an_observer->data != NULL && an_observer->data_free != NULL)
    {
      an_observer->data_free(an_observer->data);
    }
}

void
observer_destructor(observer_t* an_observer)
{
  if(an_observer != NULL)
    {
      observer_destructor_unsafe(an_observer);
    }
}

bool
observer_is_null(const observer_t* an_observer)
{
  return an_observer == NULL || an_observer->handler == NULL;
}

#define STRUCT_PROPRIETY_EQUALS(struct1, struct2, propriety) \
  ( (struct1).propriety == (struct2).propriety )

bool
observer_equals_unsafe(const observer_t* observer1, const observer_t* observer2)
{
  return
    STRUCT_PROPRIETY_EQUALS(*observer1, *observer2, handler) &&
    STRUCT_PROPRIETY_EQUALS(*observer1, *observer2, data)    &&
    STRUCT_PROPRIETY_EQUALS(*observer1, *observer2, data_free);
}

bool
observer_equals(const observer_t* observer1, const observer_t* observer2)
{
  if((observer1 == NULL && observer2 != NULL) ||
     (observer1 != NULL && observer2 == NULL))
    {
      return false;
    }
  return
    observer1 == observer2 ||
    observer_equals_unsafe(observer1, observer2);
}


EXTERN_C_END
